package com.example.customview.view

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.View
import com.example.customview.R

private val IMAGE_WIDTH = 200.dp
private val IMAGE_PADDING = 200.dp

class XferModeView(context: Context?, attrs: AttributeSet?) : View(context, attrs) {

    private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
    private val bounds = RectF()
    private var leftPadding = 0f
    private var topPadding = 0f
    private val xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP)
    private val avatarBitmap = Bitmap.createBitmap(IMAGE_WIDTH.toInt(), IMAGE_WIDTH.toInt(), Bitmap.Config.ARGB_8888)
    private val ringBitmap = Bitmap.createBitmap(IMAGE_WIDTH.toInt(), IMAGE_WIDTH.toInt(), Bitmap.Config.ARGB_8888)

    init {
        val canvas = Canvas(avatarBitmap)
        canvas.drawBitmap(getAvatar(IMAGE_WIDTH.toInt()), 0f, 0f, paint)
        canvas.setBitmap(ringBitmap)
        paint.strokeWidth = 5.dp
        paint.style = Paint.Style.STROKE
        canvas.drawOval(bounds, paint)
        paint.style = Paint.Style.FILL
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        leftPadding = width / 2f - IMAGE_WIDTH / 2
        topPadding = height / 2f - IMAGE_WIDTH / 2
        bounds.set(leftPadding, topPadding, leftPadding + IMAGE_WIDTH, topPadding + IMAGE_WIDTH)
    }

    override fun onDraw(canvas: Canvas) {
        val saveCount = canvas.saveLayer(bounds, null)
        canvas.drawOval(bounds, paint)
        paint.xfermode = xfermode
        canvas.drawBitmap(getAvatar(IMAGE_WIDTH.toInt()), leftPadding, topPadding, paint)
        paint.strokeWidth = 15.dp
        paint.style = Paint.Style.STROKE
        canvas.drawOval(bounds, paint)
        paint.xfermode = null
        canvas.restoreToCount(saveCount)
    }

    fun getAvatar(width: Int): Bitmap {
        val options = BitmapFactory.Options()
        options.inJustDecodeBounds = true
        BitmapFactory.decodeResource(resources, R.drawable.avatar_rengwuxian, options)
        options.inJustDecodeBounds = false
        options.inDensity = options.outWidth
        options.inTargetDensity = width
        return BitmapFactory.decodeResource(resources, R.drawable.avatar_rengwuxian, options)
    }
}